﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Profile;
using System.Web.Routing;
using System.Web.Security;
using Core.BOL;
using Core.DAL;
using Core.Extentions;
using Core.Utils;
using ScoutNET.Attributes;
using System.Linq;

namespace ScoutNET.Controllers
{    
    public class ProfilController : ApplicationController
    {
        #region Repositories
        private FunctionRepository fr = new FunctionRepository();
        private SectionRepository sr = new SectionRepository();
        private UsersRepository ur = new UsersRepository();
        private ImagesRepository ir = new ImagesRepository();
        private MyAlbumRepository mr = new MyAlbumRepository();
        #endregion

        [AuthorizeView(ErrorMessageKey = "Profil_Index_Error_Acces", ShowToCrawler = false)]
        public ActionResult Index()
        {
            ViewData["PageTitle"] = Resources.Profil_Index_Title;
            ViewData["PageDescription"] = Resources.Profil_Index_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_Index_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            MembershipUser mu = Membership.GetUser(User.Identity.Name);
            ProfileBase pb = ProfileBase.Create(mu.UserName);
            string roles = Roles.GetRolesForUser(mu.UserName)[0];

            ViewData["firstname"] = pb["firstname"];
            ViewData["lastname"] = pb["lastname"];
            ViewData["username"] = mu.UserName;
            ViewData["email"] = mu.Email;
            ViewData["totem"] = pb["totem"];
            ViewData["location"] = pb["location"];
            ViewData["phone"] = pb["phone"];
            ViewData["webSite"] = pb["webSite"];
            ViewData["signature"] = pb["signature"];
            ViewData["lUserSections"] = sr.GetUserSectionsByUserId((Guid)mu.ProviderUserKey);
            ViewData["sexF"] = (pb["Sex"].ToString() == "F");
            ViewData["sexM"] = (pb["Sex"].ToString() != "F");
            ViewData["avatar"] = (!string.IsNullOrEmpty((string)pb["avatar"])) ? ConfigurationManager.AppSettings["AvatarPath"] + pb["avatar"] + ".jpg" : string.Empty;
            ViewData["avatarID"] = (!string.IsNullOrEmpty((string)pb["avatar"])) ? pb["avatar"] : string.Empty;

            List<tSite_Section> lSection = sr.GetNonAdministrativeSections();
            ViewData["SlSection"] = new SelectList(lSection, "ID", "Section", pb["SectionID"].ToString());
            ViewData["lSections"] = lSection;
            ViewData["SlFunctions"] = new SelectList(fr.GetAllFunctions(), "RoleName", "RoleName", roles);

            return View();
        }

        [HttpPost]
        [AuthorizeView(ErrorMessageKey = "Profil_Index_Error_Acces", ShowToCrawler = false)]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public ActionResult Index(FormCollection fc)
        {
            MembershipUser mu = Membership.GetUser(User.Identity.Name);
            ProfileBase pb = ProfileBase.Create(mu.UserName);
            
            string roles = Roles.GetRolesForUser(mu.UserName)[0];
            List<aspnet_Role> lRoles = fr.GetAllFunctions();

            ViewData["PageTitle"] = Resources.Profil_Index_Title;
            ViewData["PageDescription"] = Resources.Profil_Index_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_Index_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            if (ValidateRegistration(fc, true, true))
            {
                bool isFunctionChanged = false;
                // Create Role
                if (!Roles.IsUserInRole(mu.UserName, fc["SlFunctions"]))
                {
                    Roles.RemoveUserFromRole(mu.UserName, roles);
                    Roles.AddUserToRole(mu.UserName, fc["SlFunctions"]);
                    isFunctionChanged = true;
                }

                //Upload file
                var file = Request.Files["avatar"];
                if (file != null && file.ContentLength > 0)
                {
                    System.IO.File.Delete(HttpContext.Server.MapPath(ConfigurationManager.AppSettings["AvatarPath"] + pb["Avatar"] + ".jpg"));
                    Guid avatarName = Guid.NewGuid();
                    pb["Avatar"] = avatarName.ToString();
                    string extention = Path.GetExtension(file.FileName);
                    Dictionary<string, int> imageSize = Imaging.GetImageSize(ImageMode.Avatar);
                    
                    BinaryReader b = new BinaryReader(file.InputStream);
                    byte[] baImage = b.ReadBytes(file.ContentLength);
                    baImage = Imaging.ResizeImage(baImage, imageSize["W"], imageSize["H"], 70);
                    string fileName = Server.MapPath(ConfigurationManager.AppSettings["AvatarPath"] + avatarName + ".jpg");
                    Files.ByteArrayToFile(fileName, baImage);
                }

                //Update Profil
                var selectedRole = lRoles.Where(p => p.RoleName == fc["SlFunctions"]).SingleOrDefault();

                pb["firstname"] = fc["firstname"];
                pb["lastname"] = fc["lastname"];
                pb["totem"] = fc["totem"];
                pb["location"] = fc["location"];
                pb["phone"] = fc["phone"];
                pb["webSite"] = fc["webSite"];
                pb["signature"] = fc["signature"].ClearHTMLTags();
                pb["SectionID"] = (lRoles[1] != selectedRole && lRoles[2] != selectedRole) ? null : (int?)int.Parse(fc["SlSection"]);
                pb["Sex"] = fc["sex"];
                pb.Save(); 

                // Update membership user
                if ((fc["SlFunctions"] == "C.U" || fc["SlFunctions"] == "Animateur") && isFunctionChanged)
                {
                    mu.IsApproved = false;

                    // Send validation mail
                    NameValueCollection nvc = HttpUtility.ParseQueryString("");
                    nvc.Add(Request.Form);
                    nvc.Add("username", mu.UserName);

                    Uri siteUrl = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);
                    string siteName = ConfigurationManager.AppSettings["SiteName"];

                    string title = string.Empty;
                    string actionProfilValidationUrl = siteUrl + Url.Action("ProfilAdminValidation", new { controller = "Mail" });
                    string body = Mail.GetMailHTML(actionProfilValidationUrl, nvc.ToString(), out title);
                    body = body.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                    tSite_Section webmasterSection = sr.GetSectionsById(8);

                    Mail.SendMail(webmasterSection.Email
                    , title
                    , body
                    , webmasterSection.Email
                    , webmasterSection.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst());

                    ViewData["ValidationMessage"] = Resources.Profil_Index_AdminFunctionChangedValidation;
                }
                else
                {
                    ViewData["ValidationMessage"] = Resources.Profil_Index_Validation;
                }
                
                mu.Email = fc["email"];

                Membership.UpdateUser(mu);

                // Update Users Section
                List<int> sectionIDs = new List<int>();
                if (fc["infoSection"] != null)
                {
                    string[] infoSection = fc["infoSection"].Split(',');
                    foreach (string sectionID in infoSection) sectionIDs.Add(Convert.ToInt32(sectionID));
                }
                
                aspnet_User u = new aspnet_User();
                u.SectionIDs = sectionIDs;
                u.UserId = (Guid)mu.ProviderUserKey;
                ur.UpdateSectionsByUserId(u);
                ur.Save();

                if ((fc["SlFunctions"] == "C.U" || fc["SlFunctions"] == "Animateur") && isFunctionChanged)
                {
                    FormsAuthentication.SignOut();
                }

                return View("Validation");
            }
            else
            {
                ViewData["firstname"] = fc["firstname"];
                ViewData["lastname"] = fc["lastname"];
                ViewData["email"] = fc["email"];
                ViewData["sexF"] = (fc["Sex"].ToString() == "F");
                ViewData["sexM"] = (fc["Sex"].ToString() != "F");
                ViewData["signature"] = fc["signature"].ClearHTMLTags();
                ViewData["totem"] = fc["totem"];
                ViewData["location"] = fc["location"];
                ViewData["phone"] = fc["phone"];
                ViewData["webSite"] = fc["webSite"];
                ViewData["SectionID"] = Convert.ToInt32(fc["SlSection"]);
                ViewData["Sex"] = fc["sex"];

                ViewData["lUserSections"] = sr.GetUserSectionsByUserId((Guid)mu.ProviderUserKey);
                List<tSite_Section> lSection = sr.GetNonAdministrativeSections();
                ViewData["SlSection"] = new SelectList(lSection, "ID", "Section", pb["SectionID"].ToString());
                ViewData["lSections"] = lSection;
                ViewData["SlFunctions"] = new SelectList(fr.GetAllFunctions(), "RoleName", "RoleName", roles);

                return View();
            }
            
        }

        [NotAuthorizeLogged]
        public ActionResult LogOn()
        {
            ViewData["PageTitle"] = Resources.Profil_Logon_Title;
            ViewData["PageDescription"] = Resources.Profil_Logon_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_Logon_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            ViewData["LoginID"] = HttpContext.Request.QueryString["loginID"];

            return View();
        }

        [HttpPost]
        [NotAuthorizeLogged]
        public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl)
        {
            ViewData["PageTitle"] = Resources.Profil_Logon_Title;
            ViewData["PageDescription"] = Resources.Profil_Logon_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_Logon_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            if (!ValidateLogOn(userName, password))
            {
                return View();
            }

            FormsAuthentication.Authenticate(userName, password);
            FormsAuthentication.SetAuthCookie(userName, rememberMe);

            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [NotAuthorizeLogged]
        public ActionResult Inscription()
        {
            ViewData["PageTitle"] = Resources.Profil_Inscription_Title;
            ViewData["PageDescription"] = Resources.Profil_Inscription_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_Inscription_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            List<tSite_Section> lSection = sr.GetNonAdministrativeSections();
            ViewData["SlSection"] = new SelectList(lSection, "ID", "Section");
            ViewData["lSections"] = lSection;
            ViewData["SlFunctions"] = new SelectList(fr.GetAllFunctions(), "RoleName", "RoleName");
            return View();
        }

        [HttpPost]
        [CaptchaValidator]
        [NotAuthorizeLogged]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken()]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public ActionResult Inscription(FormCollection fc, bool captchaValid)
        {
            ViewData["PageTitle"] = Resources.Profil_Inscription_Title;
            ViewData["PageDescription"] = Resources.Profil_Inscription_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_Inscription_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            List<aspnet_Role> lRoles = fr.GetAllFunctions();

            List<tSite_Section> lSection = sr.GetNonAdministrativeSections();
            ViewData["SlSection"] = new SelectList(lSection, "ID", "Section");
            ViewData["lSections"] = lSection;
            ViewData["SlFunctions"] = new SelectList(lRoles, "RoleName", "RoleName");

            if (ValidateRegistration(fc, captchaValid, false))
            {
                // Create user
                string userName = (!string.IsNullOrEmpty(fc["userName"])) ? fc["userName"].ToString().ToLower() : string.Empty;
                MembershipCreateStatus createStatus;
                Membership.CreateUser(userName, fc["password"], fc["email"], null, null, false, null, out createStatus);
 
                if (createStatus == MembershipCreateStatus.Success)
                {
                    ProfileBase pb = ProfileBase.Create(fc["userName"]);
                    Guid userID = (Guid)Membership.GetUser(fc["userName"]).ProviderUserKey;
                    //Upload file
                    var file = Request.Files["avatar"];
                    if (file != null && file.ContentLength > 0)
                    {
                        Guid avatarName = Guid.NewGuid();
                        pb["Avatar"] = avatarName.ToString();
                        string extention = Path.GetExtension(file.FileName);
                        Dictionary<string, int> imageSize = Imaging.GetImageSize(ImageMode.Avatar);

                        BinaryReader b = new BinaryReader(file.InputStream);
                        byte[] baImage = b.ReadBytes(file.ContentLength);
                        baImage = Imaging.ResizeImage(baImage, imageSize["W"], imageSize["H"], 70);

                        string fileName = Server.MapPath(ConfigurationManager.AppSettings["AvatarPath"] + avatarName + ".jpg");
                        Files.ByteArrayToFile(fileName, baImage);
                    }

                    // Create profile
                    var selectedRole = lRoles.Where(p => p.RoleName == fc["SlFunctions"]).SingleOrDefault();

                    pb["FirstName"] = fc["firstname"];
                    pb["LastName"] = fc["lastname"];
                    pb["Sex"] = fc["sex"];
                    pb["Totem"] = fc["totem"];
                    pb["Location"] = fc["location"];
                    pb["Phone"] = fc["phone"];
                    pb["WebSite"] = fc["webSite"];
                    pb["Signature"] = fc["signature"].ClearHTMLTags();
                    pb["SectionID"] = (lRoles[1] != selectedRole && lRoles[2] != selectedRole) ? null : (int?)int.Parse(fc["SlSection"]);
                    
                    pb.Save();

                    // Create Role
                    if (!Roles.IsUserInRole(fc["userName"], fc["SlFunctions"]))
                    {
                        Roles.AddUserToRole(fc["userName"], fc["SlFunctions"]);
                    }

                    // Create Information Section
                    if (fc["infoSection"] != null)
                    {
                        string[] infoSection = fc["infoSection"].Split(',');
                        List<int> sectionIDs = new List<int>();
                        foreach (string sectionID in infoSection) sectionIDs.Add(Convert.ToInt32(sectionID));

                        aspnet_User u = new aspnet_User();
                        u.SectionIDs = sectionIDs;
                        u.UserId = userID;
                        ur.InsertUsersSection(u);
                        ur.Save();
                    }

                    // List email STAF
                    List<string> friendsMails = new List<string>();
                    if (!string.IsNullOrEmpty(fc["friendMail1"]))
                    {
                        friendsMails.Add(fc["friendMail1"]);
                    }
                    if (!string.IsNullOrEmpty(fc["friendMail2"]))
                    {
                        friendsMails.Add(fc["friendMail2"]);
                    }
                    if (!string.IsNullOrEmpty(fc["friendMail3"]))
                    {
                        friendsMails.Add(fc["friendMail3"]);
                    }
                    
                    bool isAdmin = false;

                    tSite_Section webmasterSection = sr.GetSectionsById(8);
                    if (webmasterSection != null)
                    {
                        Uri siteUrl = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);
                        string siteName = ConfigurationManager.AppSettings["SiteName"];

                        // send STAF email
                        if (friendsMails.Count > 0)
                        {
                            string actionSTAFUrl = siteUrl + Url.Action("Staff", new { controller = "Mail" });

                            foreach (string friendsMail in friendsMails)
                            {
                                NameValueCollection postedValues = HttpUtility.ParseQueryString("");
                                postedValues.Add("SenderLastName", fc["lastname"]);
                                postedValues.Add("SenderFirstName", fc["firstname"]);

                                string title = string.Empty;
                                string body = Mail.GetMailHTML(actionSTAFUrl, postedValues.ToString(), out title);
                                body = body.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                                Mail.SendMail(friendsMail
                                , title
                                , body
                                , fc["email"]
                                , fc["firstname"] + " " + fc["lastname"]);
                            }
                        }

                        // Send validation mail
                        NameValueCollection nvc = HttpUtility.ParseQueryString("");
                        nvc.Add(Request.Form);

                        // Send contributors validation
                        if (fc["SlFunctions"] == "C.U" || fc["SlFunctions"] == "Animateur")
                        {
                            isAdmin = true;
                            string actionProfilValidationUrl = siteUrl + Url.Action("ProfilContributorValidation", new { controller = "Mail" });

                            string title = string.Empty;
                            string body = Mail.GetMailHTML(actionProfilValidationUrl, nvc.ToString(), out title);
                            body = body.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                            Mail.SendMail(fc["email"]
                            , title
                            , body
                            , webmasterSection.Email
                            , webmasterSection.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst());

                            actionProfilValidationUrl = siteUrl + Url.Action("ProfilAdminValidation", new { controller = "Mail" });
                            body = Mail.GetMailHTML(actionProfilValidationUrl, nvc.ToString(), out title);
                            body = body.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                            Mail.SendMail(webmasterSection.Email
                            , title
                            , body
                            , webmasterSection.Email
                            , webmasterSection.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst());
                        }
                        // Send User validation
                        else
                        {
                            string actionProfilValidationUrl = siteUrl + Url.Action("ProfilUserValidation", new { controller = "Mail" });

                            nvc.Add("UserID", userID.ToString());
                            
                            string title = string.Empty;
                            string body = Mail.GetMailHTML(actionProfilValidationUrl, nvc.ToString(), out title);
                            body = body.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                            Mail.SendMail(fc["email"]
                            , title
                            , body
                            , webmasterSection.Email
                            , webmasterSection.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst());
                        }
                    }

                    // Validation Message
                    ViewData["ValidationMessage"] = (isAdmin) ? Resources.Profil_Inscription_ValidationMessageAdmin : Resources.Profil_Inscription_ValidationMessageUser;
                    return View("Validation");
                }
                else
                {
                    ModelState.AddModelError("userName", ErrorCodeToString(createStatus));
                }
         
            }

            return View();
        }

        [AuthorizeView(ErrorMessageKey = "Profil_ChangePassword_Error_Access", ShowToCrawler = false)]
        public ActionResult ChangePassword()
        {
            ViewData["PageTitle"] = Resources.Profil_ChangePassword_Title;
            ViewData["PageDescription"] = Resources.Profil_ChangePassword_Description;

            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Profil_Index_Breadcrumb, "Default", "Index", "Profil", null, null);
            saBreadcrumb[2] = Resources.Profil_ChangePassword_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            ViewData["PasswordLength"] = Resources.Profil_ChangePassword_PasswordLenght.Replace("[NUM_CHARACTER]", Membership.MinRequiredPasswordLength.ToString());

            return View();
        }
        
        [HttpPost]
        [ValidateAntiForgeryToken()]
        [AuthorizeView(ErrorMessageKey = "Profil_ChangePassword_Error_Access", ShowToCrawler = false)]
        public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            ViewData["PageTitle"] = Resources.Profil_ChangePassword_Title;
            ViewData["PageDescription"] = Resources.Profil_ChangePassword_Description;

            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Profil_Index_Breadcrumb, "Default", "Index", "Profil", null, null);
            saBreadcrumb[2] = Resources.Profil_ChangePassword_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            int numChar = Membership.MinRequiredPasswordLength;

            ViewData["PasswordLength"] = Resources.Profil_ChangePassword_PasswordLenght.Replace("[NUM_CHARACTER]", numChar.ToString());

            if (!ValidateChangePassword(currentPassword, newPassword, confirmPassword))
            {
                return View();
            }
            try
            {

                if (Membership.Provider.ChangePassword(User.Identity.Name, currentPassword, newPassword))
                {
                    ViewData["ValidationMessage"] = Resources.Profil_ChangePassword_ValidationMessage.Replace("[USERNAME]",User.Identity.Name);
                    return View("Validation");
                }
                else
                {
                    ModelState.AddModelError("_FORM", Resources.Profil_ChangePassword_Error_Unknown.Replace("[NUM_CHARACTER]", numChar.ToString()));
                    return View();
                }
            }
            catch
            {
                ModelState.AddModelError("_FORM", Resources.Profil_ChangePassword_Error_Unknown.Replace("[NUM_CHARACTER]", numChar.ToString()));
                return View();
            }
        }

        [NotAuthorizeLogged]
        public ActionResult Forgot()
        {
            ViewData["PageTitle"] = Resources.Profil_RetrieveProfil_Title;
            ViewData["PageDescription"] = Resources.Profil_RetrieveProfil_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_RetrieveProfil_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            return View();
        }

        [HttpPost]
        [NotAuthorizeLogged]
        public ActionResult Forgot(FormCollection fc)
        {
            ViewData["PageTitle"] = Resources.Profil_RetrieveProfil_Title;
            ViewData["PageDescription"] = Resources.Profil_RetrieveProfil_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_RetrieveProfil_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            string userName = (!string.IsNullOrEmpty(fc["email"])) ? Membership.GetUserNameByEmail(fc["email"]) : fc["userName"];
            MembershipUser mu = null;

            if (ValidateForgot(fc, userName, out mu))
            {
                tSite_Section webmasterSection = sr.GetSectionsById(8);
                if (webmasterSection != null && mu != null)
                {
                    Uri siteUrl = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);
                    string siteName = ConfigurationManager.AppSettings["SiteName"];
                    string actionUrl = siteUrl + Url.Action("ForgotPassword", new { controller = "Mail" });

                    NameValueCollection postedValues = HttpUtility.ParseQueryString("");
                    postedValues.Add("UserID", ((Guid)mu.ProviderUserKey).ToString());

                    string title = string.Empty;
                    string body = Mail.GetMailHTML(actionUrl, postedValues.ToString(), out title);
                    body = body.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                    Mail.SendMail(mu.Email
                    , title
                    , body
                    , webmasterSection.Email
                    , webmasterSection.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst());

                    ViewData["ValidationMessage"] = Resources.Profil_RetrieveProfil_Validation_ForgotLogin;

                    return View("Validation");
                }
            }
            return View();
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult ValidationUser(Guid ID)
        {
            ViewData["PageTitle"] = Resources.Profil_ValidationUser_Title;
            ViewData["PageDescription"] = Resources.Profil_ValidationUser_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Profil_ValidationUser_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            MembershipUser mu = Membership.GetUser(ID);
            if(mu == null)
            {
                ViewData["ErrorMessage"] = Resources.Profil_ValidationUser_Error;
                return View("Error");
            }
            else
            {
                mu.IsApproved = true;
                Membership.UpdateUser(mu);
                ViewData["ValidationMessage"] = Resources.Profil_ValidationUser_Validation.Replace("[USERNAME]", mu.UserName.UppercaseFirst());
                return View("Validation");
            }
        }

        [Authorize]
        public ActionResult DeleteAvatar()
        {
            ProfileBase pb = ProfileBase.Create(User.Identity.Name);

            ViewData["AID"] = pb["Avatar"].ToString();
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult DeleteAvatar(FormCollection fc)
        {
            Guid AID = new Guid(fc["AID"].ToString());
            string imagePath = ConfigurationManager.AppSettings["AvatarPath"] + AID.ToString() + ".jpg";
            
            System.IO.File.Delete(Server.MapPath(imagePath));
            ProfileBase pb = ProfileBase.Create(User.Identity.Name);
            pb["Avatar"] = string.Empty;
            pb.Save();

            return new EmptyResult();
        }

        [AuthorizeView(ErrorMessageKey = "Profil_MonAlbum_Error_Acces", ShowToCrawler = false)]
        public ActionResult MonAlbum()
        {
            ViewData["PageTitle"] = Resources.Pages_MonAlbum_Title;
            ViewData["PageDescription"] = Resources.Pages_MonAlbum_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Pages_MonAlbum_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            MembershipUserCollection mu = Membership.FindUsersByName(User.Identity.Name);
            if (mu.Count > 0)
            {
                List<tSite_Photos_MyAlbum> lMyAlbum = mr.GetImagesByUserID((Guid)mu[User.Identity.Name].ProviderUserKey);
                if (lMyAlbum.Count > 0)
                {
                    return View("MyAlbum", lMyAlbum);
                }
                else
                {
                    ViewData["ErrorMessage"] = Resources.Profil_MonAlbum_Error_NoItem;
                    return View("Error");
                }
            }
            else
            {
                ViewData["ErrorMessage"] = Resources.Profil_MonAlbum_Error_NoAlbum;
                return View("Error");
            }

        }

        [AuthorizeView(ErrorMessageKey = "Profil_MonAlbum_Error_Acces", ShowToCrawler = false)]
        public ActionResult DeletePictureAlbum(int id)
        {
            ViewData["ID"] = id;

            return View();
        }

        [HttpPost]
        [AuthorizeView(ErrorMessageKey = "Profil_MonAlbum_Error_Acces", ShowToCrawler = false)]
        public ActionResult DeletePictureAlbum(FormCollection fc)
        {
            int ID = - 1;
            if (int.TryParse(fc["ID"], out ID))
            {
                ir.DeletePictureByImageID(ID);
                ir.Save();

                ViewData["ValidationMessage"] = Resources.Profil_DeletePictureAlbum_Confirm;

                return View("Validation", "~/Views/Shared/Iframe.Master");
            }
            return View();
        }

        [OutputCache(CacheProfile="Photo")]
        [AuthorizeView(ErrorMessageKey = "Profil_Index_Error_Acces", ShowToCrawler = false)]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public FileResult MyAlbumImageResize(int ID, string title)
        {
            byte[] baImage = Imaging.GetResizedImage(ID, ImageMode.MyAlbumPhoto, false);

            return new FileContentResult(baImage, "image/jpeg");
        }

        [OutputCache(CacheProfile="Photo")]
        [AuthorizeView(ErrorMessageKey = "Profil_Index_Error_Acces", ShowToCrawler = false)]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public FileResult MyAlbumThumbnailResizer(int ID, string title)
        {
            byte[] baImage = Imaging.GetResizedImage(ID, ImageMode.MyAlbumThumbnail, false, false);

            return new FileContentResult(baImage, "image/jpeg");
        }

        [AuthorizeView(ErrorMessageKey = "Profil_Index_Error_Acces", ShowToCrawler = false)]
        public ActionResult ZipFile()
        {
            MembershipUser mu = Membership.GetUser(User.Identity.Name);

            if (mu != null)
            {
                string[] parametres = new string[1];
                parametres[0] = ((Guid)mu.ProviderUserKey).ToString();

                KeyValuePair<TaskManagerAction, object> taskParametres = new KeyValuePair<TaskManagerAction, object>(TaskManagerAction.ZipMyALbum, parametres);
                TaskManager.AddTask(taskParametres);

                return View();
            }
            else
            {
                return View("Error404");
            }
        }

        [OutputCache(CacheProfile="Photo")]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public FileResult ImageResize(int ID, string name)
        {
            byte[] baImage = Imaging.GetResizedImage(ID, ImageMode.GalleryThumbnail, false, false);

            return new FileContentResult(baImage, "image/jpeg");
        }

        #region Validation Methods
        private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            if (String.IsNullOrEmpty(currentPassword))
            {
                ModelState.AddModelError("currentPassword", Resources.Profil_ChangePassword_Error_CurrentPwd);
            }
            if (newPassword == null || newPassword.Length < Membership.MinRequiredPasswordLength)
            {
                ModelState.AddModelError("newPassword", Resources.Profil_ChangePassword_Error_NewPwd.Replace("[NUM_CHARACTER]", Membership.MinRequiredPasswordLength.ToString()));
            }

            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", Resources.Profil_ChangePassword_Error_NotMatch);
            }

            return ModelState.IsValid;
        }

        private bool ValidateLogOn(string userName, string password)
        {
            userName = (!string.IsNullOrEmpty(userName)) ? userName.ToLower() : string.Empty;
            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", Resources.Profil_LogOn_Error_UserName);
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", Resources.Profil_LogOn_Error_Pwd);
            }
            if (!Membership.ValidateUser(userName, password))
            {
                ModelState.AddModelError("_FORM", Resources.Profil_LogOn_Error_NotFound);
            }

            return ModelState.IsValid;
        }

        private bool ValidateRegistration(FormCollection fc, bool captchaValid, bool isUpdate)
        {
            ModelState.SetModelValue("firstname", ValueProvider.GetValue("firstname"));
            ModelState.SetModelValue("lastname", ValueProvider.GetValue("lastname"));
            ModelState.SetModelValue("email", ValueProvider.GetValue("email"));
            ModelState.SetModelValue("signature", ValueProvider.GetValue("signature"));

            ModelState.SetModelValue("totem", ValueProvider.GetValue("totem"));
            ModelState.SetModelValue("sex", ValueProvider.GetValue("sex"));
            ModelState.SetModelValue("location", ValueProvider.GetValue("location"));
            ModelState.SetModelValue("phone", ValueProvider.GetValue("phone"));
            ModelState.SetModelValue("webSite", ValueProvider.GetValue("webSite"));
            ModelState.SetModelValue("signature", ValueProvider.GetValue("signature"));

            ModelState.SetModelValue("SlFunctions", ValueProvider.GetValue("SlFunctions"));
            ModelState.SetModelValue("SlSection", ValueProvider.GetValue("SlSection"));

            if (!isUpdate)
            {
                ModelState.SetModelValue("userName", ValueProvider.GetValue("userName"));
                ModelState.SetModelValue("password", ValueProvider.GetValue("password"));
                ModelState.SetModelValue("confirmPassword", ValueProvider.GetValue("confirmPassword"));

                ModelState.SetModelValue("friendMail1", ValueProvider.GetValue("friendMail1"));
                ModelState.SetModelValue("friendMail2", ValueProvider.GetValue("friendMail2"));
                ModelState.SetModelValue("friendMail3", ValueProvider.GetValue("friendMail3"));

                if (!Regex.IsMatch(fc["userName"], "^[a-zA-Z0-9]{5,15}$"))
                {
                    ModelState.AddModelError("userName", Resources.Profil_Inscription_Error_UserName);
                }

                if (!String.IsNullOrEmpty(fc["friendMail1"]) && !Validation.IsEmail(fc["friendMail1"]))
                {
                    ModelState.AddModelError("friendMail1", string.Format(Resources.Profil_Inscription_Error_FriendEmail, 1));
                }

                if (!String.IsNullOrEmpty(fc["friendMail2"]) && !Validation.IsEmail(fc["friendMail2"]))
                {
                    ModelState.AddModelError("friendMail2", string.Format(Resources.Profil_Inscription_Error_FriendEmail, 2));
                }

                if (!String.IsNullOrEmpty(fc["friendMail3"]) && !Validation.IsEmail(fc["friendMail3"]))
                {
                    ModelState.AddModelError("friendMail3", string.Format(Resources.Profil_Inscription_Error_FriendEmail, 3));
                }

                if (!captchaValid)
                {
                    ModelState.AddModelError("recaptcha_response_field", Resources.Profil_Inscription_Error_Captcha);
                }
            }

            if (String.IsNullOrEmpty(fc["firstname"]))
            {
                ModelState.AddModelError("firstname", Resources.Profil_Inscription_Error_Firstname);
            }

            if (String.IsNullOrEmpty(fc["lastname"]))
            {
                ModelState.AddModelError("lastname", Resources.Profil_Inscription_Error_Lastname);
            }

            if (String.IsNullOrEmpty(fc["email"]) || !Validation.IsEmail(fc["email"]))
            {
                ModelState.AddModelError("email", Resources.Profil_Inscription_Error_Email);
            }

            if ((fc["password"] == null || fc["password"].Length < Membership.MinRequiredPasswordLength) && !isUpdate)
            {
                ModelState.AddModelError("password", Resources.Profil_Inscription_Error_Password.Replace("[NUM_CHARACTER]", Membership.MinRequiredPasswordLength.ToString()));
            }

            if (!String.Equals(fc["password"], fc["confirmPassword"], StringComparison.Ordinal) && !isUpdate)
            {
                ModelState.AddModelError("_FORM", Resources.Profil_Inscription_Error_NotMatch);
                ModelState.AddModelError("password", string.Empty);
                ModelState.AddModelError("confirmPassword", string.Empty);
            }

            return ModelState.IsValid;
        }

        private bool ValidateForgot(FormCollection fc, string userName, out MembershipUser mu)
        {
            mu = null;

            if (string.IsNullOrEmpty(fc["email"]) && string.IsNullOrEmpty(fc["userName"]))
            {
                ModelState.SetModelValue("email", ValueProvider.GetValue("email"));
                ModelState.AddModelError("email", "Email ou pseudo non remplis");
                ModelState.AddModelError("userName", string.Empty);
            }
            else
            {
                if (!string.IsNullOrEmpty(fc["email"]))
                {
                    if (!Validation.IsEmail(fc["email"]))
                    {
                        ModelState.SetModelValue("email", ValueProvider.GetValue("email"));
                        ModelState.AddModelError("email", Resources.Profil_RetrieveProfil_Error_Email);
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(userName))
                        {
                            ModelState.SetModelValue("email", ValueProvider.GetValue("email"));
                            ModelState.AddModelError("email", "Cette adresse email n'a pas été trouvée");
                        }
                        else
                        {
                            mu = Membership.GetUser(userName);

                            if (mu == null)
                            {
                                ModelState.SetModelValue("email", ValueProvider.GetValue("email"));
                                ModelState.AddModelError("email", "Cette adresse email n'a pas été trouvée");
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(fc["userName"]))
                {
                    mu = Membership.GetUser(userName);

                    if (mu == null)
                    {
                        ModelState.SetModelValue("userName", ValueProvider.GetValue("userName"));
                        ModelState.AddModelError("userName", "Cette adresse email n'a pas été trouvée");
                    }
                }
            }
            
            return ModelState.IsValid;
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return Resources.Profil_Inscription_CreateStatus1;

                case MembershipCreateStatus.DuplicateEmail:
                    return Resources.Profil_Inscription_CreateStatus2;

                case MembershipCreateStatus.InvalidPassword:
                    return Resources.Profil_Inscription_CreateStatus3;

                case MembershipCreateStatus.InvalidEmail:
                    return Resources.Profil_Inscription_CreateStatus4;

                case MembershipCreateStatus.InvalidAnswer:
                    return Resources.Profil_Inscription_CreateStatus5;

                case MembershipCreateStatus.InvalidQuestion:
                    return Resources.Profil_Inscription_CreateStatus6;

                case MembershipCreateStatus.InvalidUserName:
                    return Resources.Profil_Inscription_CreateStatus7;

                case MembershipCreateStatus.ProviderError:
                    return Resources.Profil_Inscription_CreateStatus8;

                case MembershipCreateStatus.UserRejected:
                    return Resources.Profil_Inscription_CreateStatus9;                    

                default:
                    return Resources.Profil_Inscription_CreateStatus10;
            }
        }
        #endregion
    }
}
